package net.zjitc.controller;

import net.zjitc.pojo.Admin;
import net.zjitc.service.AdminService;
import net.zjitc.utils.APIResponse;
import net.zjitc.utils.JwtUtil;
import net.zjitc.utils.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;


    //session中

    public String login(Admin admin, Model model, HttpSession session){
        //查询当前用户是否存在
        Admin user = adminService.findByUsername(admin.getUsername(),admin.getPassword());
        if (user!=null){
            model.addAttribute("msg","登录成功");
            session.setAttribute("admin",admin);
            return "success";
        }
        model.addAttribute("msg","登录失败 ");
        return "login";
    }

    @PostMapping("login")
    @ResponseBody
    public APIResponse<Token> login(@RequestBody Admin admin){
        //查询当前用户是否存在
        Admin user = adminService.findByUsername(admin.getUsername(),admin.getPassword());
        APIResponse apiResponse = new APIResponse<>();
        if (user!=null){
            // 生成Token
            String token = JwtUtil.generateToken(admin.getUsername(),360000000);
            apiResponse.oK("登录成功",new Token(token));
            return apiResponse;
        }else {
            apiResponse.error(1000,"登录失败",null);
            return apiResponse;
        }
    }
}
